package com.xcoder.leetcode;

/**
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/
 */
public class _21_合并两个有序链表 {

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(-1);
        ListNode l0 = pre;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                l0.next = l1;
                l1 = l1.next;
            } else {
                l0.next = l2;
                l2 = l2.next;
            }
            l0 = l0.next;
        }
        // 合并完后l1和l2最多只有一个还有剩余节点，直接将新链表尾部指向这个链表即可
        l0.next = l1 == null ? l2 : l1;
        return pre.next;
    }
}
